package com.why.amallrest.interceptor;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.http.HttpStatus;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.alibaba.fastjson.JSON;
import com.why.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: mall-parent
 * @description:
 * @author: @why
 * @create: 2021-10-30 15:13
 **/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Value("mall.user.token.key")
    private String salt;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("token is:{}", token);
        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return true;
        }
        final byte[] key = salt.getBytes();
        if (StringUtils.isEmpty(token)) {
            doResponse(response, "token不存在，请检查！",20001);
            return false;
        }


        boolean flag = JWTUtil.verify(token, key);
        if (flag) {
            try {
                JWTValidator.of(token).validateDate();
                return true;
            } catch (ValidateException e) {
                doResponse(response, "token过期!",HttpStatus.HTTP_UNAUTHORIZED);
                log.error("token过期!", e);
                return false;

            }
        } else {
            return false;
        }
    }


    private void doResponse(HttpServletResponse response, String msg,int code) throws IOException {
        response.setContentType("application/json");
        String res = JSON.toJSONString(Result.error(code,msg));
        response.setContentLength(res.getBytes().length);
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(res);
        response.getWriter().flush();
    }
}
